<?php
require_once( 'CustomHttpRequest.php');
class GoogleSiteInfo_Exception extends Exception {
}

class GoogleSiteInfo {
    protected $_siteHost;
    protected $_language;
    protected $_google;

    private function _toString( &$var ) {
        if( is_string($var) ) {
            return $var;
        } elseif( is_object($var) ) {
            if( is_callable(array($var,'__toString')) ) {
                $data = $var->__toString();
                return $data;
            }
        } elseif( is_null($var) ) {
            return '';
        }
    }

    private function _stripTags( $str ) {
        $strs=explode('<',$str);
        $res=$strs[0];
        for($i=1;$i<count($strs);$i++) {
            if(!strpos($strs[$i],'>'))
                $res = $res.'&lt;'.$strs[$i];
            else 
                $res = $res.'<'.$strs[$i];
        }
        return strip_tags($res);
    }


    public function __construct( $siteHost, $lang = 'en', $google = '.com') {
        $this->_language = $lang;
        $this->_google = 'http://www.google.' .$google;
        $siteHost = $this->_toString($siteHost);
        $siteHost = preg_replace('@^http://@','',$siteHost);
        if( empty($siteHost) ) {
            throw new GoogleSiteInfo_Exception('Given site host is empty');
        }
        $siteHost = 'http://'.$siteHost;
        $this->_siteHost = $siteHost;
    }

    protected function _getHttpSiteHost() {
        return $this->_siteHost;
    }

    protected function _getSiteHost() {
        return preg_replace('@^http://@','',$this->_siteHost);
    }

    protected function _makeGoogleSearchRequest( $query, $params = null ) {
        $page = isset($params['page']) ? (int)$params['page'] : $params['page'];
        $urlData = array(
            'host' => $this->_google,
            'target' => 'search',
            'query_string' => 'hl='.$this->_language.'&lr='.$this->_language.'&q='.urlencode($query).'&ie=utf-8&oe=utf-8&btnG=Szukaj&start='.(($page-1)*10).'&lr=',
        );
        $request = new CustomHttpRequest($urlData);
        $content = $request->getContent();
        return $content;
    }


    public function getIndexedPagesAmount() {
        $query = 'site:'.$this->_siteHost;
        $content = $this->_makeGoogleSearchRequest($query);
        $content = $this->_stripTags($content);
        preg_match('/.+of about ([0-9,]+) from.+/',$content,$match);
        if( isset($match[1]) ) {
            $amount = preg_replace('/[^0-9]/','',$match[1]);
            return (int)$amount;
        } else {
            if( preg_match('/did not match/',$content) ) {
                return 0;
            }
            throw new GoogleSiteInfo_Exception('Regexp pattern havent found any pages amount');
        }
    }

    public function getInboundLinksAmount() {
        $query = 'link:'.$this->_siteHost;
        $content = $this->_makeGoogleSearchRequest($query);
        $content = $this->_stripTags($content);
        preg_match('/.+of about ([0-9,]+) linking.+/',$content,$match);
        if( isset($match[1]) ) {
            $amount = preg_replace('/[^0-9]/','',$match[1]);
            return (int)$amount;
        } else {
            if( preg_match('/did not match/',$content) ) {
                return 0;
            }
            throw new GoogleSiteInfo_Exception('Regexp pattern havent found any pages amount');
        }
    }

    public function getPositionAtKeyword( $keyword, $inPages = 10 ) {
        $keyword = $this->_toString($keyword);
        $page = 1;
        $pos = 0;
        $siteHost = $this->_getSiteHost();
        while($page < $inPages ) {
            $content = $this->_makeGoogleSearchRequest($keyword,array('page'=>$page));
            preg_match_all('/<h3.+?href="(.+?)".+?<\/h3>/mis',$content,$match);
            //print_r(Text::stripTags($content));
            foreach( $match[1] as $no => $href ) {
                $pos++;
                if( preg_match('@^http://[a-zA-Z0-9\-_.]*?'.preg_quote($siteHost).'/@',$href) ) {
                    return $pos;
                }
            }
            $page++;
        }
        return $pos;
    }
    
 
    
}
